import Vuex from 'vuex'
import { miniLogin, getUserInfo, getDefault } from '@/api/login/index'
import { base_info } from '@/api/moreMessage'

const modulesFiles = import.meta.glob('./modules/*.ts', { eager: true })
const modules = Object.keys(modulesFiles).reduce((p, n) => {
  const moduleName = n.replace(/^\.\/modules\/(.+)\.ts$/, '$1')
  const value = modulesFiles[n]
  p[moduleName] = value.default
  return p
}, {})

interface state {
  token: string
  platform: string
  userInfo: Object
  safeAreaBottom: number
  REPORTINFO: Object
  PHYSICAL: Array<Object>
  QUESTIONAIRE: Array<Object>
  FOLLOW: Array<Object>
  ISNOTICE: Boolean
  // 终端名
  CLIENTNAME: string
  // 终端类型
  CLIENTTYPE: string
}

const getters = {}
const state: state = {
  token: uni.getStorageSync('token') || '',
  userInfo: {},
  platform: '',
  safeAreaBottom: 0,
  REPORTINFO: {},
  PHYSICAL: [],
  QUESTIONAIRE: [],
  FOLLOW: [],
  ISNOTICE: false,
  CLIENTNAME: '检后小程序',
  CLIENTTYPE: 'checkAfterMini'
}
const mutations = {
  setToken(state, payload: string) {
    state.token = payload
    if (state.token) {
      uni.setStorageSync('token', payload)
    } else {
      uni.removeStorageSync('token')
    }
  },
  setPlatform(state, payload: string) {
    state.platform = payload
  },
  SET_USERINFO(state, payload: Object) {
    state.userInfo = payload
    if (String(payload) !== '{}') {
      uni.setStorageSync('userInfo', JSON.stringify(payload))
    } else {
      uni.removeStorageSync('userInfo')
    }
  },
  setSafeAreaBottom(state, payload) {
    state.safeAreaBottom = payload
  },
  SET_REPORTINFO(state, payload) {
    state.REPORTINFO = payload
  },
  SET_PHYSICAL(state, payload) {
    state.PHYSICAL = payload
  },
  SET_QUESTIONAIRE(state, payload) {
    state.QUESTIONAIRE = payload
  },
  SET_FOLLOW(state, payload) {
    state.FOLLOW = payload
  },
  SET_ISNOTICE(state, payload) {
    state.ISNOTICE = payload
  }
}

const actions = {
  getToken({ commit }) {
    return new Promise((resolve, reject) => {
      uni.login({
        success: (res) => {
          miniLogin(res.code)
            .then((res) => {
              if (res.code === 0) {
                commit('setToken', res.data.token)
                resolve()
              } else {
                reject()
              }
            })
            .catch((e) => {
              reject()
            })
        }
      })
    })
  },
  getUserInfoByToken() {
    return new Promise((resolve, reject) => {
      getUserInfo()
        .then((res) => {
          if (res) {
            resolve(res.data)
          } else {
            reject()
          }
        })
        .catch((err) => {
          reject()
        })
    })
  },
  async setUserInfo({ commit, rootState, dispatch }, payload) {
    try {
      if (!rootState.token) {
        await dispatch('getToken')
      }
      const info = await dispatch('getUserInfoByToken')
      commit('SET_USERINFO', info)

      let params = {
        userId: info.userId,
        empi: info.empi
      }
      if (info.phone && info.isVerified) {
        let notice = rootState.ISNOTICE
        if (!notice) {
          // 判断是否从通知进入
          getDefault(params.userId).then((res) => {
            info.patientInfo = Object.assign({}, res.data)
            commit('SET_USERINFO', info)
            uni.switchTab({
              url: '/pages/index/index'
            })
          })
        } else {
          getDefault(info.userId).then((res) => {
            info.patientInfo = Object.assign({}, res.data)
            commit('SET_USERINFO', info)
            uni.switchTab({
              url: '/pages/index/index'
            })
          })
        }
      } else if (!info.phone) {
        uni.redirectTo({
          url: '/pages/login/login'
        })
      } else if (!info.isVerified) {
        uni.redirectTo({
          url: '/pages/login/realName'
        })
      }
      payload && payload.success && payload.success()
    } catch (e) {
      if (payload && payload.fail) {
        payload.fail()
      } else {
        uni.showModal({
          title: '提示',
          content: '网络异常，点击确定重新登录',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              dispatch('setUserInfo')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    }
  }
}

const store = new Vuex.Store({
  getters,
  state,
  mutations,
  actions,
  modules
})

export default store
